package cn.foo;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author Frank
 * @date 07-05
 */
@Configuration//beans
@PropertySource("classpath:jdbc.properties")// <context:property-placeholder location="jdbc.properties"/>
@MapperScan(basePackages = "cn.foo.dao")//<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
@ComponentScan(basePackages = "cn.foo.service")//<context:component-scan base-package="cn.foo.service"/>
@EnableTransactionManagement
public class AppConfig {
    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Bean// <bean id="dataSource"
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource(url,username,password);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }
    @Bean// <bean id="sqlSessionFactory"
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("cn.foo.pojo");
        return sqlSessionFactoryBean.getObject();
    }

    @Bean//<bean id="txManager"
    public DataSourceTransactionManager txManager(){
        return new DataSourceTransactionManager(dataSource());
    }



}
